<? 




class Storage
{
	private $path = null;
	private $name = null;
	
	public function Storage($path)
	{
		$dir = dirname($path);
		$this->path = $path;
		if(!is_dir($dir))
		{
			ssinc('folder');
			Folder::Create($dir);
		}
		if(!file_exists($this->path.'.list'))
		{
			file_put_contents($this->path.'.list', '');
		}
	}
	
	public function Remove($name)
	{
		file_put_contents($this->path.'.list', preg_replace('#'.$name.'\t\d+\t\d+\n#', '', file_get_contents($this->path.'.list')));
	}
	
	public function Get($name, $return = true)
	{
		$f = fopen($this->path.'.list', 'r');
		while($s = fgets($f))
		{
			if(stripos($s, "$name\t") !== FALSE)
			{
				$arr = explode("\t", $s);
				if(sizeof($arr)!==3)
				{
					fclose($f);
					return false;
				}
									
				fclose($f); 
				if($return)
					return $this->_get($arr[1], $arr[2], true); 
				else
				{
					$this->_get($arr[1], $arr[2], false); 
					return true;
				}
			}
		}
		fclose($f);
	}
	public function Exists($name)
	{
		$f = fopen($this->path.'.list', 'r');
		while($s = fgets($f))
		{
			if(stripos($s, "$name\t") !== FALSE)
			{
				fclose($f); return true;
			}
		}
		fclose($f);
		return false;
	}
	public function Put($name, $path)
	{
		$fobj = fopen($path, 'r') or die('Can\'t read '.$path);
		$stat = fstat($fobj);
		$lenght = $stat['size'];
		
		$fstorage = fopen($this->path, 'a+') or die('Can\'t read '.$this->path);
		$stat = fstat($fstorage);
		$start = $stat['size'];
		
		while (!feof($fobj)) 
		{
   			$s = fread($fobj, 8192);
   			fwrite($fstorage, $s);
 		}
		fclose($fobj);fclose($fstorage);
		
		if(!$this->Exists($name))
		{
			$f = fopen($this->path.'.list', 'a');
			fwrite($f, "$name\t$start\t$lenght\n");
			fclose($f);
		}
	}
	private function _get($start, $end, $return = true)
	{
	
	$s = true;
		$f = fopen($this->path, 'r');
		fseek($f, $start);
		if($return)
			$s=fread($f, $end);
		else 
			print fread($f, $end);
		fclose($f);
		return $s;	
	}
}
?>